<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\BaseController;
use App\Models\User;
use EasyWeChat\Factory;
use Hashids\Hashids;
use Illuminate\Support\Str;

class GroupController extends BaseController
{
    public function index()
    {
        $user_id = auth('api')->id();
        $data = User::query()
                    ->with(['title:id,title','identity:user_id,identity'])
                    ->where('parent_id',$user_id)
                    ->simplePaginate();

        return $this->success($data);
    }

    public function qrcode()
    {

        $app = Factory::miniProgram(config('wechat'));

        $user = auth('api')->user();

        if ($user->min_qrocde){
            return $this->success([
                'min_qrocde' => $user->min_qrocde,
                'invite_code' => $user->invite_code
            ]);
        }

        if (!$user->invite_code){
            $hashids = new Hashids('',6);
            $user->invite_code = $hashids->encode($user->id);
            $user->save();
        }

        $response = $app->app_code->getUnlimit($user->invite_code, [
            'page' => 'pages/tabbar/index/index',
            'env_version' => 'trial',
            'check_path' => false,
            'width' => 600,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(public_path('qrcodes'), Str::uuid().'.png');
            $qrcode_url ='https://' . request()->host().'/qrcodes/'.$filename;

            $user->min_qrcode = $qrcode_url;
            $user->save();

            return $this->success([
                'min_qrocde' => $qrcode_url,
                'invite_code' => $user->invite_code
            ]);

        }

    }
}
